package com.example.xiaomiao.Controller;

import com.example.xiaomiao.DTO.AIAnalysisResponseDTO;
import com.example.xiaomiao.DTO.GetMoneyRequestDTO;
import com.example.xiaomiao.Service.AIService;
import com.example.xiaomiao.Util.JwtUtil;
import io.reactivex.rxjava3.schedulers.Schedulers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;

import static com.example.xiaomiao.Util.MyConstants.SSE_TIMEOUT;

@RestController
@RequestMapping("/ai")
public class AIController {
    @Resource
    AIService aiService;
    private static final Logger logger = LoggerFactory.getLogger(AIController.class);

    @PostMapping("/analysis")
    public SseEmitter analysis(HttpServletRequest request, @RequestBody GetMoneyRequestDTO getMoneyRequestData) {
        String token = JwtUtil.getTokenFromCookie(request);
        String id = JwtUtil.extractUsername(token);
        int userId = Integer.parseInt(id.substring(8));
        SseEmitter emitter = new SseEmitter(SSE_TIMEOUT);
        emitter.onTimeout(() -> {
            logger.warn("SSE Timeout, closing emitter");
            emitter.complete();
        });
        emitter.onCompletion(() -> logger.info("SSE Completed"));
        aiService.analysis(userId,getMoneyRequestData)
                .subscribeOn(Schedulers.io()) // 切换到 IO 线程池
                .subscribe(
                        content -> {
                            try {
                                emitter.send(new AIAnalysisResponseDTO(content));
                            } catch (IOException e) {
                                logger.error("Error sending SSE message: " + e.getMessage());
                                emitter.completeWithError(e);
                            }
                        },
                        throwable -> {
                            logger.error("Error in SSE streaming: " + throwable.getMessage());
                            emitter.completeWithError(throwable);
                        },
                        () -> {
                            logger.info("All content streamed successfully.");
                            emitter.complete();
                        }
                );
        return emitter;
    }
}
